package com.example.experiment07.interceptor;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.experiment07.component.JWTComponent;
import com.example.experiment07.exception.MyException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @description:
 * @author: YancyZhang
 * @time: 2022/6/21 15:07
 */
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private JWTComponent jwtComponent;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (token == null) {
            throw new MyException(400, "未登录");
        }
        DecodedJWT result = jwtComponent.decode(token);
        request.setAttribute("role", result.getClaim("role").asString());
        return true;
    }
}